import Vue from 'vue'
import axios from 'axios'
import { Message } from 'element-ui'

const AxiosInstance = axios.create({
  baseURL: '/api'
})
export default ({ store, redirect }) => {
  //请求拦截
  AxiosInstance.interceptors.request.use(function (config) {
    const token = sessionStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  })
  //响应拦截
  AxiosInstance.interceptors.response.use(function (config) {
    const { data } = config
    if (data.code === -2) {
      Message.error('登录过期，请重新登录')
      sessionStorage.clear()
      redirect('/login')
    }
    return data
  })
}

Vue.prototype.$axios = AxiosInstance
